package com.supervision.manage.controller;

import com.fly.base.annotation.AuthPermission;
import com.fly.base.common.DataResponse;
import com.fly.base.controller.BaseController;
import com.fly.base.redis.RedisService;
import com.supervision.manage.util.VerifyCodeUtil;
import com.supervision.manage.util.VerifyCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * @ClassName: CaptchaController
 * @description:
 * @author: whis
 * @create: 2020-03-06 09:45
 **/
@RestController
@RequestMapping("/manage/1/captcha")
@Api(tags = "验证码")
public class CaptchaController extends BaseController {

    @Autowired
    private RedisService redisService;

    /**
     * 获取验证码图片和文本(验证码文本会保存在HttpSession中)
     */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    @AuthPermission(needToken = false)
    @ApiOperation("验证码")
    public DataResponse genCaptcha() throws IOException {
        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);

        // 将验证码放到Redis里面
        String key = UUID.randomUUID().toString();
        try (Jedis jedis = redisService.getClient()) {
            jedis.setex(key, 300, verifyCode.toLowerCase());
        }

        BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 116, 36, 0, true, new Color(255, 255, 255), null, null);
        //写给浏览器
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "JPEG", stream);
        String base64 = "data:image/png;base64," + Base64.getEncoder().encodeToString(stream.toByteArray());

        return DataResponse.create().put("uuid", key).put("image", base64);
    }
}
